<template>
  <ContentCard>
    <template #header>
      <pageHeaderNew
        title="入职申请列表"
        :breadCrumb="['人事', '人事管理', '入职申请']"
        :showBack="false"
      >
        <template #buts>
          <a-button
            type="outline"
            @click="
              router.push({
                name: 'EntryApplicationSetting'
              })
            "
            >入职申请设置</a-button
          >
        </template>
      </pageHeaderNew>
    </template>

    <a-tabs lazy-load v-model="currTab" @change="changeTabs">
      <template #extra>
        <div>
          <a-dropdown
            @popup-visible-change="handleBatch"
            v-model:popup-visible="showBatch"
            @select="moreControl"
          >
            <a-button type="primary">批量操作</a-button>
            <template #content>
              <a-doption @click="audit(null)" v-show="currTab === 1"
                >批量审核</a-doption
              >
              <a-doption v-show="currTab === 3" @click="del(null)"
                >批量删除</a-doption
              >
              <a-doption :value="1" v-show="currTab === 2"
                >批量转待入职</a-doption
              >
              <a-doption :value="2" v-show="currTab === 2"
                >批量转入职申请</a-doption
              >
              <a-doption :value="3" v-show="currTab === 2"
                >批量转确认入职</a-doption
              >
            </template>
          </a-dropdown>
        </div>
      </template>
      <a-tab-pane :key="1" title="待审核">
        <TableShow :node="currTab" v-if="currTab === 1" />
      </a-tab-pane>
      <a-tab-pane :key="2" title="审核通过">
        <TableShow :node="currTab" v-if="currTab === 2" />
      </a-tab-pane>
      <a-tab-pane :key="3" title="审核不通过">
        <TableShow :node="currTab" v-if="currTab === 3" />
      </a-tab-pane>
    </a-tabs>
  </ContentCard>
  <FormHeaderSetting
    v-model:visible="setting"
    title="入职申请表头设置"
    :result-list="headerList"
    @headerSave="headerSave"
  ></FormHeaderSetting>
</template>
<script setup lang="tsx">
import VueQr from 'vue-qr/src/packages/vue-qr.vue';
import style from './style.module.less';
import { flatTree, dataTreeFilter, downloadExcelFile } from '@/utils/utils';
import { useRouter } from 'vue-router';
import {
  PutHeaderSetting,
  GetHeaderSetting,
  PostHeaderSetting
} from '@/apis/management/base/index';
import {
  GetWorkPlaceList,
  GetOrganizationList
} from '@/apis/management/organization/organizationManagement';
import { GetStaff } from '@/apis/management/personnel/baseSetting/TransactionSetting';
import {
  PutAuditEntryState,
  ChangeHumanInductionState,
  DelHumanList
} from '@/apis/management/personnel/changeManagement/inductionManagement';
import { GetBusinessModalData } from '@/apis/controltotal/index';
import { GetPosition } from '@/apis/management/organization/positionManagement';
import { GetHumanTemplateList } from '@/apis/management/human/baseSetting/humanSetting';
import IconFont from '@/components/IconFont/index.vue';
import TableTurn from '@/components/TableTurn/index.vue';
import {
  Modal,
  Tooltip,
  TableColumn,
  Message,
  Radio,
  RadioGroup,
  Tag,
  Dropdown,
  Doption
} from '@arco-design/web-vue';
import TableControlShow from '@/components/TableControlShow/index.vue';

// 选择器配置
const args = reactive({
  rowSelection: {
    type: 'checkbox',
    showCheckedAll: true,
    onlyCurrent: false
  },
  stripe: true
});
let tableRef = ref(); // 表格的ref

/* 储存选择的数据 */
let selectedList = computed(() => tableRef.value.selectedList); // 待审核表格选中的id
// const selectedList2 = computed(() => tableRef2.value.selectedList); // 审核通过表格选中的id
// const selectedList3 = computed(() => tableRef3.value.selectedList); // 审核不通过表格选中的id
// let selectedList1, // 待审核表格选中的id
//   selectedList2, // 审核通过表格选中的id
//   selectedList3; // 审核不通过表格选中的id
let currTab = ref(1); // 当前选中的tab值

let exportSettingVisible = ref(false); // 导出弹出框
let importVisible = ref(false); // 导入弹出框
let forbidList: string[] = []; // 必选的表头
let exportHeaderList = ref(); // 接口获取过来的原始表头数据
const router = useRouter();
let setting = ref(false); // 判断是否点击设置按钮
let headerList = ref(); // 接口获取过来的原始表头数据
let headerSetting = ref<any>([]); // 当前的表头数据
let orginHeaderList = ref([]); // 原始的表头数据

// 点击切换选项卡
const changeTabs = (key: number) => {
  currTab.value = key;
};

const getTableData = async (page: any) => {
  try {
    const res = await GetStaff({
      ...page,
      typeName: '1',
      auditStatus: currTab.value
    });

    res.content.forEach((item: any) => {
      item.ctlValue.forEach((element: any) => {
        item[element.ctlCode] = element.ctlValue;
      });
    });
    return Promise.resolve(res);
  } catch (error: unknown) {
    console.log(error);
  }
};

// 新增表头
const addHeader = async () => {
  //SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB
  try {
    const {
      funcCtlInfos: { children }
    } = await GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    });

    let headerListCode: any = [];
    children?.forEach((item1: any) => {
      const { subRelDetail, cnName, subCode } = item1.subDetail;
      subRelDetail?.forEach((item2: any, index2: number) => {
        headerListCode.push(item2.ctlCode);
      });
    });
    await PostHeaderSetting({
      userId: +(localStorage.getItem('userId') as string),
      ownerFuncType: 4,
      headerListCode: headerListCode.join(',')
    });

    init();
  } catch (error: unknown) {
    console.log(error);
  }
};

// 储存要特殊处理的数据
const showInfoData = reactive({
  data: {
    deptList: [], // 组织列表数据
    workPlaceList: [], // 工作地点数据
    positionList: [] // 职位列表数据
  }
});

// 处理特殊渲染的数据
const ShowInfo = (props: any) => {
  const record = props.record;
  const ctlCode = props.ctlCode;
  switch (ctlCode) {
    // 公司
    case 'CA8ABCC1480744557B3014C3454465A7E':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CA8ABCC1480744557B3014C3454465A7E']
            )?.name
          }
        </div>
      );
    // 部门
    case 'CED44AC9966904CD1AB546D309903727C':
      return (
        <div>
          {
            showInfoData.data.deptList.find(
              (item: any) =>
                item.id == record['CED44AC9966904CD1AB546D309903727C']
            )?.name
          }
        </div>
      );
    // 工作地点
    case 'CE009C2E2B542409D815F0D3D54FE0E2B':
      return (
        <div>
          {
            showInfoData.data.workPlaceList.find(
              (item: any) =>
                item.id == record['CE009C2E2B542409D815F0D3D54FE0E2B']
            )?.name
          }
        </div>
      );
    // 职位名称
    case 'C2818BAA63AE848AA845DA2E81ECB1843':
      return (
        <div>
          {
            showInfoData.data.positionList.find(
              (item: any) =>
                item.id == record['C2818BAA63AE848AA845DA2E81ECB1843']
            )?.name
          }
        </div>
      );
    default:
      break;
  }
};

// 在表格上显示的表头
const selectedHeader = computed(() => {
  const selectedHeaders: any[] = [];
  headerSetting.value.forEach((headerGroup: any, index: number) => {
    let defaultHeaders = headerGroup.heads.filter(
      (header: any) => header.isDefault === true
    );
    defaultHeaders = defaultHeaders.map((el: any) => {
      const sort = orginHeaderList.value.headerListCode
        .split(',')
        .findIndex((el2: any) => el2 === el.ctlCode);
      return {
        ...el,
        sort
      };
    });
    selectedHeaders.push(...defaultHeaders);
  });

  selectedHeaders.sort((a, b) => a.sort - b.sort);
  // 将姓名移到最前面
  const nameHeaderIndex = selectedHeaders.findIndex(
    (header) => header.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1'
  );
  if (nameHeaderIndex !== -1) {
    selectedHeaders.unshift(...selectedHeaders.splice(nameHeaderIndex, 1));
  }
  return selectedHeaders;
});

let showBatch = ref(false);
// 批量操作
const handleBatch = () => {
  if (selectedList.value.length === 0) {
    Message.error('请先选择数据');
    showBatch.value = false;
    return;
  }
};

// 前往详情
const goDetail = (id: number) => {
  router.push({
    name: 'EditTemplate',
    query: { id }
  });
};

// 表格渲染的数据
const TableShow = ({ node }: { node: number }) => {
  const Options = () => {
    return (
      <TableColumn
        width={150}
        fixed="right"
        v-slots={{
          title: () => {
            return (
              <>
                <Tooltip content="是否显示编辑">
                  <IconFont
                    type="icon-filter-def"
                    size={26}
                    style={{
                      marginRight: '10px',
                      cursor: 'pointer'
                    }}
                  />
                </Tooltip>
                <Tooltip content="表头设置">
                  <IconFont
                    type="icon-setting-def"
                    size={26}
                    style={{
                      cursor: 'pointer'
                    }}
                    onClick={isHeaderSetting}
                  />
                </Tooltip>
              </>
            );
          },
          cell: ({ record }) => {
            return (
              <>
                {node === 1 && (
                  <Tooltip content="审核">
                    <IconFont
                      onClick={() => audit(record.id)}
                      type="icon-daishenhe"
                      size={26}
                      style={{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }}
                    />
                  </Tooltip>
                )}
                {
                  <Tooltip content="查看详情">
                    <IconFont
                      type="icon-details-def"
                      size={26}
                      style={{
                        marginRight: '10px',
                        cursor: 'pointer'
                      }}
                      onClick={() => goDetail(record.id)}
                    />
                  </Tooltip>
                }
                {node === 2 && (
                  <Tooltip content="更多操作">
                    <Dropdown
                      onSelect={moreItemControl}
                      v-slots={{
                        content: () => {
                          return (
                            <>
                              <Doption value={1}>转待入职</Doption>
                              <Doption value={2}>转入职申请</Doption>
                              <Doption value={3}>转入职办理</Doption>
                            </>
                          );
                        }
                      }}
                    >
                      <IconFont
                        onClick={() => singleControl(record)}
                        type="icon-more-def"
                        size={26}
                        style={{
                          cursor: 'pointer'
                        }}
                      />
                    </Dropdown>
                  </Tooltip>
                )}
                {node !== 2 && (
                  <Tooltip content="删除">
                    <IconFont
                      onClick={() => del(record.id)}
                      type="icon-delete"
                      size={26}
                      style={{
                        cursor: 'pointer'
                      }}
                    />
                  </Tooltip>
                )}
              </>
            );
          }
        }}
      ></TableColumn>
    );
  };

  return (
    <>
      <TableTurn tableData={getTableData} args={args} ref={tableRef}>
        <TableColumn
          width={80}
          fixed="left"
          v-slots={{
            title: '序号',
            cell: ({ rowIndex }) => {
              return rowIndex + 1;
            }
          }}
        ></TableColumn>
        {selectedHeader.value.map((item, index) => (
          <TableColumn
            title={item.ctlCnName}
            dataIndex={item.ctlCode}
            width={200}
            fixed={
              item.ctlCode === 'C62B8DC31189847E0972B5D8F721404B1' ? 'left' : ''
            }
            sortable={{ sortDirections: ['ascend', 'descend'] }}
            key={index}
            v-slots={{
              cell: ({ record }) => {
                return (
                  <TableControlShow
                    selectedHeader={selectedHeader}
                    showCtlCodeArr={showCtlCodeArr}
                  />
                );
              }
            }}
          ></TableColumn>
        ))}
        <TableColumn
          width={100}
          fixed="right"
          v-slots={{
            title: '审核状态',
            cell: () => {
              return (
                <Tag
                  class={style.enable}
                  color={
                    node === 1
                      ? '#d9d9d9'
                      : node === 2
                      ? 'rgb(var(--green-1))'
                      : 'rgb(var(--danger-1))'
                  }
                  style={{
                    color:
                      node === 1
                        ? '#666'
                        : node === 2
                        ? 'rgb(var(--green-6))'
                        : 'rgb(var(--danger-6))',
                    '--enable':
                      node === 1
                        ? '#666'
                        : node === 2
                        ? 'rgb(var(--green-6))'
                        : 'rgb(var(--danger-6))'
                  }}
                >
                  {node === 1 ? '待审核' : node === 2 ? '通过' : '不通过'}
                </Tag>
              );
            }
          }}
        ></TableColumn>
        <Options />
      </TableTurn>
    </>
  );
};

// 初始化数据
const init = async () => {
  const [
    headerSettingRes,
    businessModalDataRes,
    humanListRes,
    deptListRes,
    workPlaceListRes,
    positionListRes
  ] = await Promise.all([
    // 获取表头
    GetHeaderSetting({
      ownerFuncType: 4,
      userId: +(localStorage.getItem('userId') as string)
    }),
    // 控件数据
    GetBusinessModalData({
      funcCode: 'SER_FUNCB6EB0EC09FFA4476B1F61D0E9F5B5FBB'
    }),
    // 人员列表
    GetHumanTemplateList({
      pageNumber: 0,
      pageSize: -1
    }),
    // 组织列表
    GetOrganizationList({}),
    // 工作地点
    GetWorkPlaceList({
      pageNumber: 0,
      pageSize: -1
    }),
    GetPosition({
      pageNumber: 0,
      pageSize: -1
    })
  ]);

  orginHeaderList.value = headerSettingRes;
  headerSetting.value = [];
  const headerChildren = businessModalDataRes.funcCtlInfos.children;
  headerChildren.forEach((child: any, index: number) => {
    headerSetting.value.push({
      collectionName: child.subDetail.cnName,
      collectionCode: child.subDetail.subCode,
      heads: child.subDetail.subRelDetail.map((subDetail: any) => {
        const isDefault = headerSettingRes.headerListCode.includes(
          subDetail.ctlCode
        );
        return {
          ...subDetail,
          isDefault
        };
      })
    });
  });
  exportHeaderList.value = headerSetting.value;
  if (headerSettingRes.headerListCode.length < 1) {
    addHeader();
  }
  showInfoData.data.deptList = flatTree(dataTreeFilter(deptListRes));
  showInfoData.data.workPlaceList = workPlaceListRes.content;
  showInfoData.data.positionList = positionListRes.content;
};
init();

// 表格中需要特殊渲染的template
const showCtlCodeArr = [
  'CA8ABCC1480744557B3014C3454465A7E',
  'CED44AC9966904CD1AB546D309903727C',
  'CE009C2E2B542409D815F0D3D54FE0E2B',
  'C2818BAA63AE848AA845DA2E81ECB1843'
];

// 是否显示表头
const isHeaderSetting = async () => {
  try {
    setting.value = !setting.value;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 表头设置返回的自定义事件
const headerSave = async (totalList: any, used: any, unused: any) => {
  try {
    const id = orginHeaderList.value.id;
    const headerListCode = used.map((item: any) => item.ctlCode).join(',');
    await PutHeaderSetting({
      id,
      userId: +localStorage.getItem('userId')!,
      ownerFuncType: 4,
      headerListCode
    });
    headerSetting.value = totalList;
    orginHeaderList.value.headerListCode = headerListCode;
  } catch (error: unknown) {
    console.log(error);
  }
};

// 审批弹框
const audit = (id: number | null) => {
  let auditStatus = ref(2);

  const content = () => {
    return (
      <RadioGroup v-model={auditStatus.value}>
        <Radio value={2}>通过</Radio>
        <Radio value={3}>拒绝</Radio>
      </RadioGroup>
    );
  };

  const onOk = async () => {
    try {
      if (!id && selectedList.value.length < 1) {
        Message.error('请至少选择一项！');
        return;
      }
      await PutAuditEntryState({
        ids: selectedList.value.length > 0 ? selectedList.value : [id],
        auditStatus: auditStatus.value
      });
      tableRef.value.selectedList = [];
      refresh();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  Modal.open({
    title: '审核',
    content,
    onOk
  });
};

let isMoreSelect = ref(false); // 储存单个item移动、合并的值
// 更多操作按钮
const moreControl = (key: number) => {
  isMoreSelect.value = true;
  if (key === 1) {
    changeState('是否确认转待入职', 2);
  } else if (key === 2) changeState('是否确认转入职申请', 3);
  else if (key === 3) changeState('是否确认转确认入职', 4); // 这里传4 因为同时要在花名册和入职办理列表里面同时显示
};

let singleSelectId = 0; // 储存单个item移动、合并的id
let singleSelectData = {}; // 储存单个item移动、合并的值

// 点击三个小点事件
const singleControl = (record: any) => {
  singleSelectData = record;
  singleSelectId = record.id;
  isMoreSelect.value = false;
};
// 表格中的三个小点按钮的下拉菜单
const moreItemControl = (key: number) => {
  if (key === 1) {
    changeState('是否确认转待入职', 2);
  } else if (key === 2) changeState('是否确认转入职申请', 3);
  else if (key === 3) changeState('是否确认转确认入职', 4);
};

// key 2转待入职、3入职申请、4入职办理列表
const changeState = (title: string, key: 2 | 3 | 4) => {
  const content = () => {
    return <div>{title}</div>;
  };

  const onOk = async () => {
    try {
      await ChangeHumanInductionState({
        ids: isMoreSelect.value ? selectedList.value : [singleSelectId],
        type: key // 待入职为2
      });
      tableRef.value.selectedList = [];
      refresh();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  Modal.open({
    title,
    content,
    onOk
  });
};

// 删除入职信息
const del = async (id: number | null) => {
  const content = () => {
    return <div>是否确认删除?</div>;
  };
  const onOk = async () => {
    try {
      // await DelHumanList({
      //   ids: isMoreSelect.value ? selectedList.value : [id]
      // });
      await ChangeHumanInductionState({
        ids: isMoreSelect.value ? selectedList.value : [singleSelectId],
        type: 8 // 转为放弃入职列表
      });
      tableRef.value.selectedList = [];
      refresh();
    } catch (error: unknown) {
      console.log(error);
    }
  };

  Modal.open({
    title: '是否确认删除',
    content,
    onOk
  });
};

const refresh = () => {
  tableRef.value.loadData();
};
</script>
<style lang="less" scoped>
.arco-btn {
  margin-right: 20px;
}
</style>
